import { defineStore } from 'pinia'
import { login, getUserInfo, logout } from '@/api/user'
import type { ILoginForm, IUserInfo } from '@/types'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null as IUserInfo | null
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    username: (state) => state.userInfo?.username || ''
  },

  actions: {
    async login(loginForm: ILoginForm) {
      try {
        const { token } = await login(loginForm)
        this.token = token
        localStorage.setItem('token', token)
        await this.getUserInfo()
      } catch (error) {
        throw error
      }
    },

    async getUserInfo() {
      try {
        const data = await getUserInfo()
        this.userInfo = data
        return data
      } catch (error) {
        throw error
      }
    },

    async logout() {
      try {
        await logout()
        this.token = ''
        this.userInfo = null
        localStorage.removeItem('token')
      } catch (error) {
        console.error('Logout failed:', error)
      }
    }
  }
})
